﻿using System.Globalization;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using BoldBrick.OneIntranet.HR.Resources;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Linq;

namespace BoldBrick.OneIntranet.HR.FieldTypes
{
	public class InstalledLanguagesChoiceControl : BaseFieldControl
	{
		#region ------ Value ----------------------------------------------------------------------

		public override object Value
		{
			get
			{
				EnsureChildControls();

				if (this.dropDownList.SelectedItem == null || (!this.Field.Required && this.dropDownList.SelectedIndex == 0))
					return null;

				uint lcid;
				if (uint.TryParse(this.dropDownList.SelectedItem.Value, out lcid))
					return lcid;

				return null;
			}
			set
			{
				EnsureChildControls();
				if (value != null)
				{
					this.dropDownList.SelectedValue = value.ToString();
				}
			}
		}

		#endregion

		#region ------ Controls -------------------------------------------------------------------

		protected DropDownList dropDownList;

		protected override void CreateChildControls()
		{
			base.CreateChildControls();

			// create main div
			HtmlGenericControl divMain = new HtmlGenericControl("div")
			{
				ID = "divMain"
			};
			this.Controls.Add(divMain);

			// create drop down
			dropDownList = new DropDownList
			{
				ID = "dropDownListLCID"
			};
			divMain.Controls.Add(dropDownList);

			CreateListItems();
		}

		private void CreateListItems()
		{
			uint language = SPContext.Current.Web.Language;

			if (this.dropDownList.Items.Count > 0)
				return;

			bool isRequired = this.Field.Required;

			// add (none) item if field is not required
			if (!isRequired)
			{
				string itemNone = ResourceBuilder.GetResource("InstalledLanguagesChoiceControl_ItemNone_Title", language);
				this.dropDownList.Items.Add(new ListItem(itemNone, null));
			}

			ListItem[] listItems = SPContext.Current.Web.RegionalSettings.InstalledLanguages.OfType<SPLanguage>()
				.Select(spLanguage => new CultureInfo(spLanguage.LCID))
				.Select(ci => new ListItem(ci.DisplayName, ci.LCID.ToString()))
				.OrderBy(item => item.Text)
				.ToArray();

			this.dropDownList.Items.AddRange(listItems);
		}

		protected override void RenderFieldForDisplay(HtmlTextWriter output)
		{
			if (this.ItemFieldValue == null)
				return;

			int langauge;
			if (int.TryParse(this.ItemFieldValue.ToString(), out langauge))
			{
				CultureInfo ci = new CultureInfo(langauge);
				output.Write(ci.DisplayName);
			}
		}

		#endregion

		#region ------ Validation -----------------------------------------------------------------

		public override void Validate()
		{
			base.Validate();

			if (!this.Field.Required)
				return;

			if (this.Value == null)
				this.IsValid = false;
		}

		#endregion
	}
}
